import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { readUsers, writeUsers, generateId } from './data';
import { User } from '@/types';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';

// 注册用户
export async function registerUser(username: string, password: string): Promise<{ success: boolean; message: string; user?: User }> {
  const users = readUsers();
  
  // 检查用户名是否已存在
  if (users.some(u => u.username === username)) {
    return { success: false, message: '用户名已存在' };
  }

  // 加密密码
  const hashedPassword = await bcrypt.hash(password, 10);

  const newUser: User = {
    id: generateId(),
    username,
    password: hashedPassword,
    isAdmin: false,
    createdAt: new Date().toISOString(),
  };

  users.push(newUser);
  writeUsers(users);

  return { success: true, message: '注册成功', user: newUser };
}

// 登录用户
export async function loginUser(username: string, password: string): Promise<{ success: boolean; message: string; token?: string; user?: User }> {
  const users = readUsers();
  const user = users.find(u => u.username === username);

  if (!user) {
    return { success: false, message: '用户名或密码错误' };
  }

  const isValid = await bcrypt.compare(password, user.password);
  if (!isValid) {
    return { success: false, message: '用户名或密码错误' };
  }

  const token = jwt.sign(
    { userId: user.id, username: user.username, isAdmin: user.isAdmin },
    JWT_SECRET,
    { expiresIn: '7d' }
  );

  return { success: true, message: '登录成功', token, user };
}

// 验证 Token
export function verifyToken(token: string): { userId: string; username: string; isAdmin: boolean } | null {
  try {
    const decoded = jwt.verify(token, JWT_SECRET) as any;
    
    // 从数据库实时读取用户信息，确保权限是最新的
    const users = readUsers();
    const user = users.find(u => u.id === decoded.userId);
    
    if (!user) {
      return null;
    }
    
    return {
      userId: decoded.userId,
      username: decoded.username,
      isAdmin: user.isAdmin, // 使用数据库中的最新权限
    };
  } catch {
    return null;
  }
}

// 获取用户信息
export function getUserById(userId: string): User | null {
  const users = readUsers();
  const user = users.find(u => u.id === userId);
  if (!user) return null;
  
  // 不返回密码
  const { password, ...userWithoutPassword } = user;
  return userWithoutPassword as User;
}

